/**
 * @Title: SignGradeServiceImpl.java
 * @Package com.hanyong.admin.service.signGrade
 * @Description: TODO(用一句话描述该文件做什么)
 * @author Li
 * @date 2018年10月31日 下午3:22:43
 * @version V1.0
 */
package com.hyfrogx.modules.sign.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.utils.RedisUtils;
import com.hyfrogx.modules.sign.entity.IntegralConfig;
import com.hyfrogx.modules.app.service.IntegralConfigService;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.FrogxTaskCode;
import com.hyfrogx.modules.app.utils.StringUtils;
import com.hyfrogx.modules.manage.service.task.TaskService;
import com.hyfrogx.modules.sign.dao.SignGradeDao;
import com.hyfrogx.modules.sign.entity.SignGrade;
import com.hyfrogx.modules.sign.service.SignGradeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Li
 * @ClassName: SignGradeServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2018年10月31日 下午3:22:43
 */
@Service("signGradeService")
@Slf4j
public class SignGradeServiceImpl extends ServiceImpl<SignGradeDao, SignGrade> implements SignGradeService {
  @Autowired
  private IntegralConfigService configService;
  @Autowired
  private UserService userService;

	@Autowired
	private TaskService hyTaskService;
	/*@Autowired
  private HyScoreOrderService orderService;*/

  @Autowired
  RedisUtils redisUtils;
  private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Integer sign(Long customerId) throws Exception {
    log.info("签到接口");
    Date date = new Date();
    // 获取今天的日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
    // //测试修改为分钟
    String dateString = sdf.format(date);
    log.info("-----今天是:" + dateString + "日");

    // 获取昨天的日期
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -1);
    Date date1 = calendar.getTime();
    String yesterday = sdf.format(date1);
    log.info("-----昨天是:" + yesterday + "日");

    //获取前一小时
     /*Calendar calendar = Calendar.getInstance();
     calendar.setTime(date); calendar.add(Calendar.MINUTE ,-1);
		 Date date1 = calendar.getTime(); String yesterday = sdf.format(date1);*/


    // 获取今天的签到信息
    SignGrade todaySign = (SignGrade) redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(customerId + dateString);
    if (ObjectUtil.isNull(todaySign)) {
      SignGrade record = this.baseMapper.getRecordBydayAndUid(customerId, dateString);
      if (ObjectUtil.isNotNull(record)) {
        //缓存签到信息，生命周期两天
        if (!addSignToRedis(customerId + dateString, JSON.toJSONString(record), 172800)) {
          return -1;
        }
        ;
        todaySign = record;
      }
    }

    log.info("-----今天签到信息:" + todaySign);

    // 获取昨天的签到信息
    SignGrade yesterdaySign = (SignGrade) redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(customerId + yesterday);
    if (ObjectUtil.isNull(yesterdaySign)) {
      SignGrade record = this.baseMapper.getRecordBydayAndUid(customerId, yesterday);
      if (ObjectUtil.isNotNull(record)) {
        if (!addSignToRedis(customerId + dateString, JSON.toJSONString(record), 86400)) {
          return -1;
        }
        yesterdaySign = record;
      }
    }

    log.info("-----昨天天签到信息:" + yesterdaySign);

    int grade;
    IntegralConfig config = new IntegralConfig();

		/*HyScoreOrder order = new HyScoreOrder();
		order.setUid(customerId);
		order.setCreatedate(date);
		order.setType(ScoreConsumeType.sgin.getCode());
		order.setYid(Constants.admin_uid);*/
    //log.info("-----订单信息:" + order);

		if ( ObjectUtil.isNotNull(todaySign)) {
			log.info("-----今天已经签到过了" + customerId);
			return 0;
		}
		// 如果今天没有签到
		if ( ObjectUtil.isNull(todaySign)) {
			log.info("------今天还没有签到过，可以进行签到操作~" + customerId);
			if ( ObjectUtil.isNull(todaySign)) {
				log.info("------昨天还没有签到，今天是第一天签到哦~" + customerId);
				config.setDay(1);
				grade = configService.getConfig(config).getRuleGrade();
				SignGrade record = new SignGrade();
				record.setGrade(grade);
				record.setSignDate(Integer.valueOf(dateString));
				record.setCreateTime(new Date());
				record.setUid(customerId);
				record.setDelFlag(0);
				record.setGradeType(0);
				record.setSuccRecord(1);
				this.baseMapper.insert(record);
				log.info("----签到记录写入" + record);
				userService.addScore(customerId.longValue(), grade);
				log.info("----积分记录写入,用户id:" + customerId + "积分：" + grade);
				//新版积分系统
				hyTaskService.addSignScore(customerId,FrogxTaskCode.TaskCode.SGIN,grade);

        // 生成订单
          /*order.setCoin(grade);
          order.setTotal(grade);
          Integer resutl = orderService.add(order);
          if (resutl < 1) {
            log.info("-----用户id" + customerId + "日期" + date + "今日签到信息" + todaySing + "昨日签到信息" + yesterdaySing
                + "订单" + order + "订单写入结果：" + resutl);
            return -1;
          }*/

        log.info("------今天是用户" + customerId + "第1天签到,获得积分" + grade + "分~");

        /**
         * 将签到信息以Hash形式存储到Redis中，并设定过期时间为2天
         */
        if (!addSignToRedis(customerId + dateString, JSON.toJSONString(record), 172800)) {
          return -1;
        }
        return grade;
      }

    }
    SignGrade record = this.baseMapper.getRecordBydayAndUid(customerId, yesterday);
    if (yesterdaySign.getSuccRecord() < 6) {
      log.info("-----昨天有签到记录~--" + customerId);
      config.setDay(yesterdaySign.getSuccRecord() + 1);
      grade = configService.getConfig(config).getRuleGrade();
      record.setGrade(grade);
      try {
        record.setSignDate(Integer.valueOf(dateString));
      } catch (NumberFormatException e) {
        e.printStackTrace();
      }
      record.setCreateTime(new Date());
			record.setUid(customerId);
			record.setDelFlag(0);
			record.setGradeType(0);
			record.setSuccRecord(yesterdaySign.getSuccRecord() + 1);
			record.setGradeId(null);
			this.baseMapper.insert(record);
			userService.addScore(customerId.longValue(), grade);
			//新版积分系统
			hyTaskService.addSignScore(customerId,FrogxTaskCode.TaskCode.SGIN,grade);
			// 生成订单
			/*order.setCoin(grade);
			order.setTotal(grade);
			Integer resutl = orderService.add(order);
			if (resutl < 1) {
				log.info("-------用户id" + customerId + "日期" + date + "今日签到信息" + todaySing + "昨日签到信息" + yesterdaySing
						+ "订单" + order);
				return -1;
			}*/

      //将签到信息以Hash形式存储到Redis中，并设定过期时间为2天
      if (!addSignToRedis(customerId + dateString, JSON.toJSONString(record), 172800)) {
        return -1;
      }
      log.info(
        "------今天是用户" + customerId + "第" + yesterdaySign.getSuccRecord() + 1 + "天签到,获得积分" + grade + "分~");
      return grade;
    } else if (yesterdaySign.getSuccRecord() == 6) {
      config.setDay(8);
      grade = configService.getConfig(config).getRuleGrade();
      config.setDay(7);// 额外奖励
      int grade2 = configService.getConfig(config).getRuleGrade();
      int result = grade + grade2;
      record.setGrade(result);
      try {
        record.setSignDate(Integer.valueOf(dateString));
      } catch (NumberFormatException e) {
        e.printStackTrace();
      }
      record.setCreateTime(new Date());
			record.setUid(customerId);
			record.setDelFlag(0);
			record.setGradeType(0);
			record.setGradeId(null);
			record.setSuccRecord(7);
			this.baseMapper.insert(record);
			userService.addScore(customerId.longValue(), result);
			//新版积分系统
			hyTaskService.addSignScore(customerId,FrogxTaskCode.TaskCode.SGIN,result);

      // 生成订单
        /*order.setCoin(result);
        order.setTotal(result);
        Integer resutl = orderService.add(order);
        if (resutl < 1) {
          log.info("------用户id" + customerId + "日期" + date + "今日签到信息" + todaySing + "昨日签到信息" + yesterdaySing
              + "订单" + order);
          return -1;
        }*/

      //将签到信息以Hash形式存储到Redis中，并设定过期时间为2天
      if (!addSignToRedis(customerId + dateString, JSON.toJSONString(record), 172800)) {
        return -1;
      }
      ;

      log.info("------今天是用户" + customerId + "第7天签到,获得积分" + result + "分~");
			return result;
		} else if (yesterdaySign.getSuccRecord() == 7) {
			log.info("------满签一周重新开始" + customerId);
			config.setDay(1);
			grade = configService.getConfig(config).getRuleGrade();
			record.setGrade(grade);
			record.setSignDate(Integer.valueOf(dateString));
			record.setCreateTime(new Date());
			record.setUid(customerId);
			record.setDelFlag(0);
			record.setGradeType(0);
			record.setGradeId(null);
			record.setSuccRecord(1);
			this.baseMapper.insert(record);
			userService.addScore(customerId.longValue(), grade);
			//新版积分系统
			hyTaskService.addSignScore(customerId, FrogxTaskCode.TaskCode.SGIN,grade);

      // 生成订单
        /*order.setCoin(grade);
        order.setTotal(grade);
        Integer resutl = orderService.add(order);
        if (resutl < 1) {
          log.info("------用户id" + customerId + "日期" + date + "今日签到信息" + todaySing + "昨日签到信息" + yesterdaySing
              + "订单" + order);
          return -1;
        }*/


      //将签到信息以Hash形式存储到Redis中，并设定过期时间为2天
      if (!addSignToRedis(customerId + dateString, JSON.toJSONString(record), 172800)) {
        return -1;
      }
      log.info("------今天是用户" + customerId + "第1天签到,获得积分" + grade + "分~");
      return grade;
    }
		/*log.info("------用户id" + customerId + "日期" + date + "今日签到信息" + todaySing + "昨日签到信息" + yesterdaySing + "订单"
				+ order);*/
    return -1;
  }

  @Override
  public Integer isSign(Long uid) throws Exception {
    Date date = new Date();
    // 获取今天的日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String dateString = sdf.format(date);
    log.info("-----今天是:" + dateString + "日-----");

    SignGrade todaySign = (SignGrade) redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(uid + dateString);
    if (ObjectUtil.isNull(todaySign)) {
      SignGrade record = this.baseMapper.getRecordBydayAndUid(uid, dateString);
      if (ObjectUtil.isNotNull(record)) {
        addSignToRedis(uid + dateString, JSON.toJSONString(record), 172800);
        return 1;
      } else {
        return 0;
      }
    }
    return 1;
  }

  @Override
  public SignGrade getSignRecord1(Long customerId) throws Exception {
    log.info("------获取签到记录接口");
    IntegralConfig config = new IntegralConfig();
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
    String dateString = sdf.format(date);
    log.info("-----今天是:" + dateString + "日-----");

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -1); // 获取昨天
    // calendar.add(Calendar.MINUTE, -1); //获取前一小时
    Date date1 = calendar.getTime();
    String yesterday = sdf.format(date1);

    // 获取今天的签到信息
    SignGrade todaySign = (SignGrade) redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(customerId + dateString);

    if (ObjectUtil.isNull(todaySign)) {
      SignGrade record = this.baseMapper.getRecordBydayAndUid(customerId, dateString);
      if (ObjectUtil.isNotNull(record)) {
        addSignToRedis(customerId + dateString, JSON.toJSONString(record), 172800);
        todaySign = record;
      }
    }
    // 获取昨天的签到信息
    SignGrade yesterdaySign = (SignGrade) redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(customerId + dateString);
    if (ObjectUtil.isNull(yesterdaySign)) {
      SignGrade record = this.baseMapper.getRecordBydayAndUid(customerId, yesterday);
      if (ObjectUtil.isNotNull(record)) {

        addSignToRedis(customerId + dateString, JSON.toJSONString(record), 86400);
        yesterdaySign = record;
      }
    }

    if (ObjectUtil.isNull(todaySign)) {
      SignGrade grade = new SignGrade();
      grade.setGrade(0);
      grade.setTodayIsSign(0);
      if (ObjectUtil.isNull(yesterdaySign)) {
        grade.setSuccRecord(0);
        log.info("------用户id" + customerId + "日期" + date + "签到信息" + grade);
        return grade;
      }
      if (yesterdaySign.getSuccRecord() == 7) { // 昨天已签满一周了
        grade.setSuccRecord(0);
        log.info("------用户id" + customerId + "日期" + date + "签到信息" + grade);
        return grade;
      }
      log.info("------用户id" + customerId + "日期" + date + "今日签到信息" + todaySign + "昨日签到信息" + yesterdaySign);
      return yesterdaySign;
    }
    todaySign.setTodayIsSign(1);
    config.setDay(todaySign.getSuccRecord());
    int grade1 = configService.getConfig(config).getRuleGrade();
    todaySign.setGrade(grade1);
    if (todaySign.getSuccRecord() == 7) {
      config.setDay(8);
      int grade2 = configService.getConfig(config).getRuleGrade();
      todaySign.setGrade(grade2 + grade1);
    }
    // 获取当天应得的积分
    log.info("------用户id" + customerId + "日期" + date + "今日签到信息" + todaySign + "昨日签到信息" + yesterdaySign);
    return todaySign;
  }

	/*@Override
	public List<HyScoreOrder> findSignRecordByPage(ScoreOrderPage page) {
		List<HyScoreOrder> result = orderService.findSignRecordByPage(page);
		return result;
	}*/

	/*@Override
	public Integer getScore(Integer uid) throws Exception {
		Integer score = (Integer) scoreManager.get("score", uid);
		if (score == null) {
			return 0;
		}
		return score;
	}*/


  public boolean addSignToRedis(String uidDate, String record, long expire) throws Exception {
    if (!StringUtils.isBlank(record)) {
      log.info("SIGN:" + record);
      redisUtils.putExpire(FrogConstant.RedisKey.SIGN, String.valueOf(uidDate), record, expire);
      log.info("更新SIGN到redis");
      log.info("uid:" + uidDate + ",SIGN:" + record);
      return true;
    }
    log.info("签到信息空-----" + "uidDate:" + uidDate + ",record" + record + ",expire:" + expire);
    return false;
  }


}
